package com
{
	import flash.utils.Dictionary;

	/**
	 * 事件分发器 
	 */	
	public class Dispatcher
	{
		public var observers:Dictionary;
		private var mapping:Dictionary;
		public function Dispatcher()
		{
			super();
			observers = new Dictionary();
			mapping = new Dictionary;
		}
		
		private static var instance:Dispatcher;
		private static function getInstance():Dispatcher{
			if(instance == null){
				instance = new Dispatcher();
			}
			return instance;
		}
		
		private function add(type:String,call:Function, module:String=null, method:String=null):void{
			var funcs:Array = observers[type];
			mapping[call] = {'module':module, 'method':method};
			if(funcs == null){
				funcs = []; 
				observers[type] = funcs;
			}else{
				if(funcs.indexOf(call) != -1){
					return;
				}
			}
			funcs.push(call);
		}
		
		private function remove(type:String,call:Function):void{
			var funcs:Array = observers[type];
			if(funcs){
				var index:int = funcs.indexOf(call);
				if(index != -1){
					funcs.splice(index,1);
				}
			}
		}
		
		private function execute(type:String,param:Object):void{
			var funcs:Array = observers[type];
			if(funcs == null){
				return;
			}
			for(var i:int = funcs.length - 1; i >= 0; i--)
			{
				var func:Function = funcs[i];
				if(param == null){
					func();
				}else{
					func(param);
				}				
			}
		}
		
		public static function dispatch(type:String,param:Object=null):void{
			getInstance().execute(type,param);
		}
		
		public static function register(type:String,call:Function, module:String=null, method:String=null):void{
			getInstance().add(type,call,module,method);
		}
		
		public static function remove(type:String,call:Function):void{
			getInstance().remove(type,call);
		}
	}
}
